<template>
	<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical" class="form-box">
		<a-row v-for="(item, index) in formOption" :key="index" :gutter="75">
			<a-col :span="8" v-for="v in item" :key="v.prop">
				<a-form-item :name="v.prop" v-if="!v.isrequire">
					<div slot="label" class="labelCla brfr">
						<span class="label-fon">{{ v.label }}</span>
						<!-- <span class="label-fon">{{ appAccess }}</span> -->
						<a-tooltip v-if="v.description" placement="topLeft" :title="v.description"
							arrow-point-at-center>
							<QuestionCircleOutlined style="color: rgb(150, 150, 150)" />
						</a-tooltip>
					</div>
					<a-input v-if="v.type === 'text'" v-model:value="formData[v.prop]" :maxlength="v.maxlength"
						:placeholder="v.placeholder" allow-clear />
					<a-select v-if="v.type === 'select'" v-model:value="formData[v.prop]" :placeholder="v.placeholder"
						:options="v.option" allow-clear />
					<a-radio-group v-if="v.type === 'radio'" v-model:value="formData[v.prop]" :options="radioOption"
						:name="v.prop" @change="radioChange" />
				</a-form-item>
				<a-form-item :name="v.prop" :label="v.label" v-if="v.isrequire">
					<a-input v-if="v.type === 'text'" v-model:value="formData[v.prop]" :placeholder="v.placeholder"
						:disabled="v.prop === 'singlepointUrl'" allow-clear />
					<a-input v-if="v.type === 'pcUrl'" v-model:value="formData[v.prop]" :placeholder="v.placeholder"
						@change="pcUrlChange" allow-clear />
				</a-form-item>
			</a-col>
		</a-row>
		<div>
			<a-row v-for="(item, index) in formOptionDb" :key="index" :gutter="75">
				<a-col :span="8" v-for="(v, i) in item" :key="v.prop">
					<a-form-item :name="v.prop">
						<div slot="label" class="labelCla" :class="{ brfr: isPcTodo === '1' }">
							<span class="label-fon">{{ v.label }}</span>
							<a-tooltip v-if="v.description" placement="topLeft" :title="v.description"
								arrow-point-at-center>
								<QuestionCircleOutlined style="color: rgb(150, 150, 150)" />
							</a-tooltip>
						</div>
						<a-input v-if="v.type === 'text'" v-model:value="formData[v.prop]" :placeholder="v.placeholder"
							allow-clear />
						<a-select v-if="v.type === 'select'" v-model:value="formData[v.prop]"
							:placeholder="v.placeholder" :options="v.option" allow-clear />
					</a-form-item>
				</a-col>
			</a-row>
		</div>
		<div>
			<a-row v-for="(item, index) in formOptionDy" :key="index" :gutter="75">
				<a-col :span="8" v-for="(v, i) in item" :key="v.prop">
					<a-form-item :name="v.prop">
						<div slot="label" class="labelCla" :class="{ brfr: isPcTodo === '1' && isPcReadtodo === '1' }">
							<span class="label-fon">{{ v.label }}</span>
							<a-tooltip v-if="v.description" placement="topLeft" :title="v.description"
								arrow-point-at-center>
								<QuestionCircleOutlined style="color: rgb(150, 150, 150)" />
							</a-tooltip>
						</div>
						<a-input v-if="v.type === 'text'" v-model:value="formData[v.prop]" :placeholder="v.placeholder"
							allow-clear />
						<a-select v-if="v.type === 'select'" v-model:value="formData[v.prop]"
							:placeholder="v.placeholder" :options="v.option" />
					</a-form-item>
				</a-col>
			</a-row>
		</div>

		<a-row :gutter="75">
			<a-col :span="8">
				<a-form-item label="兼容性" name="compatibility">
					<a-checkbox-group v-model:value="formData.compatibility" :options="compatibleOptions" />
				</a-form-item>
			</a-col>
			<a-col :span="8">
				<a-form-item label="认证状态" name="pcAuthType">
					<a-select v-model:value="formData.pcAuthType" placeholder="基本认证"
						:options="tool.dictList('CERTIFIED')" allow-clear />
				</a-form-item>
			</a-col>
			<!-- <a-col :span="8">
                <a-form-item label="需求编号" name="demandnumber">
                    <a-input v-model:value="formData.demandnumber" placeholder="提交审批后自动生成" />
                </a-form-item>
            </a-col> -->
			<a-col :span="8">
				<a-form-item label="门户端应用logo" name="pcLogo">
					<div class="upload-box">
						<a-upload v-model:file-list="fileList" name="avatar" list-type="picture-card"
							class="avatar-uploader" :customRequest="customRequest" :accept="fileImgType"
							:before-upload="beforeUpload" @change="handleChange" @preview="handlePreview">
							<div v-if="fileList?.length == 0">
								<plus-outlined></plus-outlined>
								<div class="ant-upload-text">上传图片</div>
							</div>
						</a-upload>
						<div class="annotation">
							<div class="tit1">*注</div>
							<div>1.应用logo需要满足UI/UE规范;</div>
							<div>2.需要上传.png/.jpg/.jpeg格式文件;</div>
							<div>3.文件大小为不超过200K;</div>
						</div>
					</div>
				</a-form-item>
			</a-col>
		</a-row>
		<a-row :gutter="75">
			<a-col :span="8">
				<a-form-item label="pc状态" name="pcStatus">
					<a-select v-model:value="formData.pcStatus" placeholder="请选择" :options="statusData"
						:field-names="{ label: 'name', value: 'key' }" allow-clear />
				</a-form-item>
			</a-col>
		</a-row>
		<a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
			<img alt="example" style="width: 100%" :src="imageUrl" />
		</a-modal>
	</a-form>
</template>

<script setup name="PortalForm">
import fileApi from '@/api/dev/fileApi'
import sysConfig from '@/config/index'
import tool from '@/utils/tool'
import { message } from 'ant-design-vue'
import { cloneDeep } from 'lodash-es'
const fileUrl = import.meta.env.VITE_FILE_URL
const fileImgType = '.jpg,.png,.jpeg,'
const formRef = ref()
// 表单数据
const formData = ref({
	isAuth: '1',
	isSinglepoint: '1',
	pcVersion: '1.0',
	pcLogo: '',
	pendingCategory: '',
	pendingDatasourceUrl: '',
	pendingDatasourceType: '',
	pendingDatasourceUsername: '',
	pendingDatasourcePassword: '135790',
	pendingTablename: '',
	pendingUserMail: '',
	readingCategory: '',
	readingDatasourceUrl: '',
	readingDatasourceType: '',
	readingDatasourceUsername: '',
	readingDatasourcePassword: '135790',
	readingTablename: '',
	readingUserMail: '',
	pcVersionNote: '',
	singlepointUrl: '',
	compatibility: '',
	pcAuthType: '',
	pcShortName: '',
	pcTutorials: '',
	pcUrl: '',
	batchReadUrl: '',
	pcStatus: '',
	threeSystemName: '',
	appInfoKeywords: '',
	isHideLogo: ''
})

const statusData = inject('statusData')
// 单选option
const radioOption = [
	{ label: '是', value: '1' },
	{ label: '否', value: '0' }
]
const valiUrl = async (_, value) => {
	if (!value) {
		return Promise.reject('请输入')
	}
	if (/[\u4E00-\u9FA5]/g.test(value)) {
		return Promise.reject('不能输入汉字!')
	}
	return Promise.resolve()
}
const valiFont = async (_, value) => {
	if (!value) {
		return Promise.reject('请输入版本说明')
	}
	if (value.length < 5) {
		return Promise.reject('不能少于5个字!')
	}
	return Promise.resolve()
}
// 兼容option
const compatibleOptions = ['IE8', 'IE9', 'IE10', 'IE11', 'chrome', 'firefox', '其他']
const changeRulesDB = reactive({
	pendingCategory: [{ required: true, message: '请输入待办所属分类', trigger: 'blur' }],
	pendingDatasourceUrl: [{ required: true, message: '请输入待办稽核地址', trigger: 'blur' }],
	pendingDatasourceType: [{ required: true, message: '请输入数据库类型', trigger: 'blur' }],
	pendingDatasourceUsername: [{ required: true, message: '请输入数据库账号', trigger: 'blur' }],
	// pendingDatasourcePassword: [{ required: true, message: '请输入数据库密码', trigger: 'blur' }],
	pendingTablename: [{ required: true, message: '请输入待办核视图地址', trigger: 'blur' }],
	pendingUserMail: [{ required: true, message: '请输入对端系统管理人邮箱', trigger: 'blur' }]
})
const changeRulesDY = reactive({
	readingCategory: [{ required: true, message: '请输入待办所属分类', trigger: 'blur' }],
	readingDatasourceUrl: [{ required: true, message: '请输入待阅稽核地址', trigger: 'blur' }],
	readingDatasourceType: [{ required: true, message: '请输入数据库类型', trigger: 'blur' }],
	readingDatasourceUsername: [{ required: true, message: '请输入数据库账号', trigger: 'blur' }],
	readingDatasourcePassword: [{ required: true, message: '请输入数据库密码', trigger: 'blur' }],
	readingTablename: [{ required: true, message: '请输入待阅核视图地址', trigger: 'blur' }],
	readingUserMail: [{ required: true, message: '请输入对端系统管理人邮箱', trigger: 'blur' }]
})
const rules = [{ required: true, validator: valiUrl, tirgger: 'blur' }]
// 默认要校验的
const formRules = reactive({
	pcVersionNote: [{ required: true, validator: valiFont, trigger: 'blur' }],
	isAuth: [{ required: true, message: '', trigger: 'blur' }],
	isSinglepoint: [{ required: true, message: '', trigger: 'blur' }],
	singlepointUrl: [{ required: true, message: '单点地址', tirgger: 'blur' }],
	compatibility: [{ required: true, message: '请选择兼容性', trigger: 'blur' }],
	pcAuthType: [{ required: true, message: '请选择认证状态', trigger: 'blur' }],
	pcLogo: [{ required: true, message: '请选择logo', trigger: 'blur' }],
	pcShortName: [{ required: true, message: '请输入应用简称', trigger: 'blur' }],
	pcTutorials: [{ required: true, message: '请输入应用教程', trigger: 'blur' }],
	pcUrl: [{ required: true, validator: valiUrl, trigger: 'blur' }],
	batchReadUrl: [{ required: true, message: '请输入批量已阅地址', trigger: 'blur' }],
	...changeRulesDB,
	...changeRulesDY
})
const formOption = [
	[
		// { label: '版本号', type: 'text', prop: 'pcVersion', placeholder: '请输入版本号', description: '多是以1.0开始的' },
		{
			label: '应用关键字',
			type: 'text',
			prop: 'appInfoKeywords',
			placeholder: '请输入应用关键字'
		},
		{
			label: '版本说明',
			type: 'text',
			prop: 'pcVersionNote',
			placeholder: '请输入版本说明',
			description: '针对该版本的说明'
		},
		{
			label: '是否鉴权',
			type: 'radio',
			prop: 'isAuth',
			placeholder: '',
			option: radioOption,
			description:
				'鉴权的应用需在应用访问角色列表中绑定角色，应用仅该角色内的用户可见；非鉴权应用默认全省或全国可见，根据应用范围控制。'
		},
		{
			label: '是否单点',
			type: 'radio',
			prop: 'isSinglepoint',
			placeholder: '',
			option: radioOption,
			description: '接入单点后可以通过双门户单点进入该应用'
		},
		{
			label: '是否展示图标',
			type: 'radio',
			prop: 'isHideLogo',
			placeholder: '',
			option: radioOption,
			description: '门户端应用是否在应用中心中隐藏图标'
		},
		// {
		// 	label: '门户端应用上线时间',
		// 	type: 'date',
		// 	prop: 'pcOnlineTime',
		// 	placeholder: '',
		// },
	],
	[
		// { label: '是否显示', type: 'radio', prop: 'is_show', placeholder: '', option: radioOption, description: '指该应用在前台用户侧可正常显示，若否则该应用不在前台展示，但可正常推待办。' },
		{
			label: '应用地址',
			isrequire: true,
			type: 'pcUrl',
			prop: 'pcUrl',
			placeholder: '请输入应用地址'
		},

		{
			label: '单点地址',
			isrequire: true,
			type: 'text',
			prop: 'singlepointUrl',
			placeholder: '单点地址',
			description: '应用跳转地址'
		},

		{
			label: '应用简称',
			type: 'text',
			prop: 'pcShortName',
			placeholder: '请输入应用简称',
			maxlength: 6,
			description: '应用简称不能超过6个字'
		},
		{
			label: '应用教程',
			type: 'text',
			prop: 'pcTutorials',
			placeholder: '请输入应用教程'
		}
	],
	[
		{
			label: '批量已阅地址',
			isrequire: true,
			type: 'text',
			prop: 'batchReadUrl',
			placeholder: '请输入单点地址',
			description: '不能提供https的地址'
		}
	]
]
const formOptionDb = [
	[
		{
			label: '待办所属分类',
			type: 'select',
			prop: 'pendingCategory',
			placeholder: '请输入待办所属分类',
			option: tool.dictList('TODO_TYPE'),
			description: ''
		},
		{
			label: '待办稽核地址',
			type: 'text',
			prop: 'pendingDatasourceUrl',
			placeholder: '请输入待办稽核地址',
			description: '应用接入待办url地址'
		},
		{
			label: '数据库类型',
			type: 'text',
			prop: 'pendingDatasourceType',
			placeholder: '请输入数据库类型',
			description: '常用的数据库类型'
		}
	],
	[
		{
			label: '数据库账号',
			type: 'text',
			prop: 'pendingDatasourceUsername',
			placeholder: '请输入数据库账号',
			description: ''
		},
		// {
		// 	label: '数据库密码',
		// 	type: 'text',
		// 	prop: 'pendingDatasourcePassword',
		// 	placeholder: '请输入数据库密码',
		// 	description: ''
		// },
		{
			label: '待办核视图地址',
			type: 'text',
			prop: 'pendingTablename',
			placeholder: '请输入待办核视图地址',
			description: '待办表名称'
		}
	],
	[
		{
			label: '对端系统管理人邮箱',
			type: 'text',
			prop: 'pendingUserMail',
			placeholder: '请输入对端系统管理人邮箱',
			description: ''
		}
	]
]
const formOptionDy = [
	[
		{
			label: '待阅所属分类',
			type: 'select',
			prop: 'readingCategory',
			placeholder: '请输入待阅所属分类',
			option: tool.dictList('TODO_TYPE'),
			description: ''
		},
		{
			label: '待阅稽核地址',
			type: 'text',
			prop: 'readingDatasourceUrl',
			placeholder: '请输入待阅稽核地址',
			description: '应用接入待阅url地址'
		},
		{
			label: '数据库类型',
			type: 'text',
			prop: 'readingDatasourceType',
			placeholder: '请输入数据库类型',
			description: '常用的数据库类型'
		}
	],
	[
		{
			label: '数据库账号',
			type: 'text',
			prop: 'readingDatasourceUsername',
			placeholder: '请输入数据库账号',
			description: ''
		},
		// {
		// 	label: '数据库密码',
		// 	type: 'text',
		// 	prop: 'readingDatasourcePassword',
		// 	placeholder: '请输入数据库密码',
		// 	description: ''
		// },
		{
			label: '待阅核视图地址',
			type: 'text',
			prop: 'readingTablename',
			placeholder: '请输入待阅核视图地址',
			description: '待阅表名称'
		}
	],
	[
		{
			label: '对端系统管理人邮箱',
			type: 'text',
			prop: 'readingUserMail',
			placeholder: '请输入对端系统管理人邮箱',
			description: ''
		}
	]
]

const fileList = ref([])
const loading = ref(false)
const imageUrl = ref('')
let previewVisible = ref(false)
/*变更编辑  开始*/
const editDate = JSON.parse(tool.session.get('editDateCL'))
onMounted(() => {
	Object.keys(formData.value).forEach((v) => {
		formData.value[v] = editDate[v]
	})
	if (formData.value.pcLogo) {
		if (formData.value.pcLogo.includes('group')) {
			fileList.value = [{ url: `${sysConfig.FULL_URL}${formData.value.pcLogo}` }]
			imageUrl.value = `${sysConfig.FULL_URL}${formData.value.pcLogo}`
		} else {
			fileList.value = formData.value.pcLogo ? JSON.parse(formData.value.pcLogo) : []
			fileList.value.forEach((item) => {
				item.url = `${fileUrl}/${item.url}`
			})
		}
	}
})

const isEdit = computed(() => {
	return editDate.value && editDate.value.pcPropertiesList.every((v) => v)
})

/*变更编辑  结束*/

// 是否单点变化事件
const radioChange = (e) => {
	const { name, value } = e.target
	if (name === 'isSinglepoint') {
		console.log(value)
		if (value === '1') {
			// 单点地址必填
			formRules.singlepointUrl[0].required = true
		} else {
			formRules.singlepointUrl[0].required = false
			formData.value.singlepointUrl = null
		}
	}
}
const pcUrlChange = (e) => {
	const { value } = e.target
	if (value) {
		if (formData.value.isSinglepoint == '1') {
			formData.value.singlepointUrl = value
		}
	}
}

// 自定义上传
const customRequest = (file) => {
	// 后端需要接受的参数是 formData数据，
	const form = new FormData()
	form.append('file', file.file)
	fileApi
		.uploadCosReturnUrlPub(form)
		.then((res) => {
			let arr = [{ name: file.file.name, url: res }]
			formData.value.pcLogo = JSON.stringify(arr)
			file.onSuccess(res, file.file)
			file.status = 'done'
		})
		.catch((err) => {
			setTimeout(() => {
				file.onError()
			}, 1000)
		})
}
const getBase64 = (img, callback) => {
	const reader = new FileReader()
	reader.addEventListener('load', () => callback(reader.result))
	reader.readAsDataURL(img)
}
const handleChange = (info) => {
	if (info.file.status === 'uploading') {
		loading.value = true
		return
	}
	if (info.file.status === 'done') {
		// Get this url from response in real world.
		getBase64(info.file.originFileObj, (base64Url) => {
			imageUrl.value = base64Url
			loading.value = false
		})
	}
	if (info.file.status === 'error') {
		loading.value = false
		fileList.value = []
		// message.error('上传失败')
	}
	if (info.file.status === 'removed') {
		formData.value.pcLogo = ''
	}
}
const beforeUpload = (file) => {
	const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
	if (!isJpgOrPng) {
		message.error('图片类型不对')
	}
	const isLt2K = file.size / 1024 < 200
	if (!isLt2K) {
		message.error('图片大小不超过200K')
	}
	return isJpgOrPng && isLt2K
}
const handlePreview = () => {
	previewVisible.value = true
}
const handleCancel = () => {
	previewVisible.value = false
}

// 监听是否接入待办修改待办相关必填非必填
const isPcTodo = inject('isPcTodo')
const formArr = []
watch(
	isPcTodo,
	(newData) => {
		Object.keys(formRules).forEach((v) => {
			if (v.includes('pending') || v.includes('reading')) {
				formRules[v][0].required = newData == '1' ? true : false
			}
		})
		// 根据待办选择是否切换待办待阅数据
		if (newData == '1') {
			// 待办选择是
			if (isEdit.value) {
				// 如果是修改,赋值
				Object.keys(changeRulesDB).forEach((v) => {
					formData.value[v] = editDate.value.pcPropertiesList[0][v]
				})
				Object.keys(changeRulesDY).forEach((v) => {
					formData.value[v] = editDate.value.pcPropertiesList[0][v]
				})
				Object.keys(formRules).forEach((v) => {
					if (v.includes('pending')) {
						formRules[v][0].required = newData == '1' ? true : false
					}
				})
			}
		} else {
			// 待办选择否-清空
			Object.keys(changeRulesDB).forEach((v) => {
				formData.value[v] = ''
			})
			Object.keys(changeRulesDY).forEach((v) => {
				formData.value[v] = ''
			})
			Object.keys(formRules).forEach((v) => {
				if (v.includes('pending')) {
					formRules[v][0].required = newData == '1' ? true : false
				}
			})
		}
	},
	{ deep: true, immediate: true }
)
// 监听是否接入待阅修改待阅相关必填非必填
const isPcReadtodo = inject('isPcReadtodo')
watch(
	isPcReadtodo,
	(newData) => {
		// console.log(newData)
		Object.keys(formRules).forEach((v) => {
			if (v.includes('reading')) {
				formRules[v][0].required = newData == '1' ? true : false
			}
		})
		formRules.batchReadUrl[0].required = newData == '1' ? true : false
	},
	{ deep: true, immediate: true }
)

// input内容发生变化 给待阅赋值
const handleChangeInput = (e) => {
	const { value, id } = e.target
	const key = id.split('_').pop().replace('pen', 'rea')
	formData.value[key] = value
}
const handleChangeSelect = (value) => {
	formData.value['readingCategory'] = value
}

// 表单验证
const handleValidate = () => {
	return new Promise((resolve, reject) => {
		resolve(formData.value)
		// formRef.value
		// 	.validate()
		// 	.then(() => {
		// 		console.log('成功')
		// 		resolve(formData.value)
		// 	})
		// 	.catch(() => {
		// 		console.log('失败')
		// 		resolve(false)
		// 	})
	})
}
defineExpose({ handleValidate, formData })
</script>

<style lang="less" scoped>
.form-box {
	margin-top: 14px;

	.upload-box {
		display: flex;

		.annotation {
			font-size: 12px;
			color: rgb(150, 150, 150);
			line-height: 22px;
			margin-left: 10px;

			.tit1 {
				color: rgb(194, 0, 0);
			}
		}
	}

	.labelCla {
		padding: 0 0 8px;

		.label-fon {
			margin-right: 10px;
		}
	}

	&-inp {
		border-radius: 4px;
		border: 1px solid rgb(206, 206, 206);
	}
}

// .labelCla::before {
//     display: inline-block;
//     margin-right: 4px;
//     color: var(--highlight-color);
//     font-size: 14px;
//     font-family: SimSun, sans-serif;
//     line-height: 1;
//     content: '*';
// }

.brfr::before {
	display: inline-block;
	margin-right: 4px;
	color: var(--highlight-color);
	font-size: 14px;
	font-family: SimSun, sans-serif;
	line-height: 1;
	content: '*';
}
</style>
<style>
.avatar-uploader>.ant-upload {
	width: 104px;
	height: 104px;
}

.ant-upload-select-picture-card i {
	font-size: 32px;
	color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
	margin-top: 8px;
	color: #666;
}
</style>
